import {Upload} from 'antd';
import type {UploadFile, UploadProps} from 'antd/es/upload/interface';
import React, {useState} from 'react';
import {PlusOutlined} from '@ant-design/icons';
import {filePath} from 'api/file'
import {getCookie} from 'utils/cookies'
import {useMount} from 'utils'


/*
* num 上传最大数量
*
*
* */
interface PropsType {
    num?: number,
    path?: string,
    onResult?: (data: object[]) => void,
    onChange?: (data: any) => void,
    picture?: string
}


const token = getCookie('mic-token')
export default function UploadImg(prop: PropsType) {
    const {num = 1, path = '', onResult, onChange: onChangeProps, picture} = prop
    // console.log(prop)
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const getRrl: (data: any[]) => string = (data) => {
        let str = ''
        data.forEach(item => {
            if (num === 1) {
                str = item.response.data.url
            } else {
                str += ((str.length > 0 ? ';' : '') + item.response.data.url)
            }
        })
        return str
    }
    const props: UploadProps = {
        onRemove: file => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFileList(newFileList);
            onResult?.(newFileList)
            onChangeProps?.(getRrl(newFileList))
            return false
        },
        // maxCount: num,
        action: filePath,
        data: {
            'type': 'images',
            'path': path
        },
        headers: {
            Authorization: 'Bearer ' + token
        },
        showUploadList: true,
        onChange: ({event, file, fileList}) => {
            // console.log(event, file)
            const newFileList = ([...fileList, file].slice(-num))
            if (!event && file.status === 'done' && file.response) {
                onResult?.(newFileList)
                onChangeProps?.(getRrl(newFileList))
            }
            setFileList(newFileList);

        },
        fileList
    };
    useMount(() => {
        const imgArr = picture?.split(';').map((item, i) => {
            const str = Date.now() + '-' + (i + 1)
            return {
                uid: 'rc-upload-' + str,
                name: '图片' + str,
                thumbUrl: item
            };
        })
        if (imgArr) setFileList(imgArr)
    })
    return (
        <>
            {fileList.map(item => {
                return item.name
            })}
            <Upload listType="picture-card" {...props}>
                {fileList.length > num ? null : <PlusOutlined/>}
            </Upload>
        </>
    );
};